package cn.wolfcode.shrio;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

public class MyAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Employee currentUser = UserContext.getCurrentUser();
        if (currentUser.isAdmin()){
            info.addStringPermission("*:*");
            info.addRole("admin");
        }else{
            List<Role> roles = roleMapper.selectByEmpId(currentUser.getId());
            roles.forEach(role -> {
                info.addRole(role.getSn());
            });
            List<String> strings = permissionMapper.selectByEmpId(currentUser.getId());
            info.addStringPermissions(strings);
        }
        /*info.addRoles(Arrays.asList("hr","seller"));
        info.addStringPermissions(Arrays.asList("employee:list","employee:save"));*/
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        Object username = authenticationToken.getPrincipal();
        Employee employee = employeeMapper.selectByUsername((String) username);
        if (employee != null){
            return new SimpleAuthenticationInfo(employee,
                    employee.getPassword(),
                    this.getName());
        }
        return null;
    }
}
